from django.db import models
from spider.models import CrawlTask
import uuid


class Company(models.Model):
    """企业信息模型"""
    company_name = models.CharField(max_length=200, unique=True, verbose_name="企业名称")
    unified_social_credit_code = models.CharField(max_length=30, unique=True, verbose_name="统一社会信用代码")
    company_info = models.JSONField(default=dict, blank=True, verbose_name="企业信息")
    qualification_info = models.JSONField(default=dict, blank=True, verbose_name="资质信息")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_company'
        verbose_name = '企业信息'
        verbose_name_plural = '企业信息'
        indexes = [
            models.Index(fields=['company_name']),
            models.Index(fields=['unified_social_credit_code']),
        ]

    def __str__(self):
        return self.company_name


class Project(models.Model):
    """项目信息模型"""
    project_code = models.CharField(max_length=100, unique=True, verbose_name="项目编号")
    project_name = models.CharField(max_length=500, verbose_name="项目名称")
    owner_name = models.CharField(max_length=200, verbose_name="业主单位")
    proxy_company = models.CharField(max_length=200, blank=True, verbose_name="代理机构")
    project_type = models.CharField(max_length=100, blank=True, verbose_name="项目类型")
    service_period = models.CharField(max_length=200, blank=True, verbose_name="服务期限")
    budget_amount = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True, verbose_name="预算金额")
    extra_data = models.JSONField(default=dict, blank=True, verbose_name="扩展数据")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='projects', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_project'
        verbose_name = '项目信息'
        verbose_name_plural = '项目信息'
        indexes = [
            models.Index(fields=['project_code']),
            models.Index(fields=['project_name']),
            models.Index(fields=['owner_name']),
        ]

    def __str__(self):
        return f"{self.project_code} - {self.project_name}"


class TenderAnnouncement(models.Model):
    """招标公告模型"""
    announcement_date = models.DateTimeField(verbose_name="公告日期")
    source_platform = models.CharField(max_length=100, verbose_name="来源平台")
    original_url = models.URLField(verbose_name="原始URL")
    announcement_info = models.JSONField(default=dict, blank=True, verbose_name="公告信息")
    project_name = models.CharField(max_length=500, blank=True, verbose_name="项目名称")
    owner_name = models.CharField(max_length=200, blank=True, verbose_name="建设单位")
    proxy_company = models.CharField(max_length=200, blank=True, verbose_name="代理机构")
    budget_amount = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True, verbose_name="公告预算金额")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tender_announcements', verbose_name="关联项目")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='tender_announcements', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_tender_announcement'
        verbose_name = '招标公告'
        verbose_name_plural = '招标公告'
        indexes = [
            models.Index(fields=['announcement_date']),
            models.Index(fields=['source_platform']),
            models.Index(fields=['original_url']),
            models.Index(fields=['project_name']),
            models.Index(fields=['owner_name']),
            models.Index(fields=['budget_amount']),
        ]

    def __str__(self):
        return f"招标公告 - {self.original_url}"


class BidOpeningRecord(models.Model):
    """开标记录模型"""
    opening_time = models.DateTimeField(verbose_name="开标时间")
    opening_location = models.CharField(max_length=500, blank=True, verbose_name="开标地点")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='bid_opening_records', verbose_name="关联项目")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='bid_opening_records', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_bid_opening_record'
        verbose_name = '开标记录'
        verbose_name_plural = '开标记录'
        indexes = [
            models.Index(fields=['opening_time']),
        ]

    def __str__(self):
        return f"开标记录 - {self.opening_time}"


class BidOpeningDetail(models.Model):
    """开标详情模型"""
    bid_price = models.DecimalField(max_digits=15, decimal_places=2, verbose_name="投标价格")
    bid_status = models.CharField(max_length=50, verbose_name="投标状态")
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='bid_opening_details', verbose_name="投标公司")
    bid_opening_record = models.ForeignKey(BidOpeningRecord, on_delete=models.CASCADE, related_name='bid_opening_details', verbose_name="开标记录")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='bid_opening_details', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_bid_opening_detail'
        verbose_name = '开标详情'
        verbose_name_plural = '开标详情'
        unique_together = ('company', 'bid_opening_record')
        indexes = [
            models.Index(fields=['bid_price']),
            models.Index(fields=['bid_status']),
        ]

    def __str__(self):
        return f"开标详情 - {self.company.company_name}"


class BidEvaluationResult(models.Model):
    """评标结果模型"""
    announcement_date = models.DateTimeField(verbose_name="公示日期")
    original_url = models.URLField(verbose_name="原始URL")
    evaluation_result_title = models.CharField(max_length=500, null=True, blank=True, default='', verbose_name="评标结果标题")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='bid_evaluation_results', verbose_name="关联项目")
    opening_record = models.ForeignKey('BidOpeningRecord', on_delete=models.SET_NULL, null=True, blank=True, related_name='evaluation_results', verbose_name="关联开标记录")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='bid_evaluation_results', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_bid_evaluation_result'
        verbose_name = '评标结果'
        verbose_name_plural = '评标结果'
        unique_together = ('announcement_date', 'project')
        indexes = [
            models.Index(fields=['announcement_date']),
            models.Index(fields=['original_url']),
            models.Index(fields=['opening_record']),
        ]

    def __str__(self):
        return f"评标结果 - {self.original_url}"


class BidCandidate(models.Model):
    """中标候选人模型"""
    candidate_rank = models.PositiveIntegerField(verbose_name="候选人排名")
    bid_price = models.DecimalField(max_digits=15, decimal_places=2, verbose_name="投标价格")
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='bid_candidates', verbose_name="候选公司")
    bid_evaluation_result = models.ForeignKey(BidEvaluationResult, on_delete=models.CASCADE, related_name='bid_candidates', verbose_name="评标结果")
    candidate_info = models.JSONField(default=dict, blank=True, verbose_name="候选人信息")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='bid_candidates', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_bid_candidate'
        verbose_name = '中标候选人'
        verbose_name_plural = '中标候选人'
        unique_together = ('candidate_rank', 'bid_evaluation_result')
        indexes = [
            models.Index(fields=['candidate_rank']),
            models.Index(fields=['bid_price']),
        ]

    def __str__(self):
        return f"中标候选人 - {self.company.company_name} (排名第{self.candidate_rank})"


class WinningResultAnnouncement(models.Model):
    """中标结果公示模型"""
    announcement_date = models.DateTimeField(verbose_name="公告日期")
    original_url = models.URLField(verbose_name="原始URL")
    winning_company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='winning_result_announcements', verbose_name="中标公司")
    winning_companies = models.ManyToManyField(Company, related_name='winning_result_announcements_m2m', verbose_name="中标公司（联合体）", blank=True)
    winning_amount = models.DecimalField(max_digits=15, decimal_places=2, verbose_name="中标金额")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='winning_result_announcements', verbose_name="关联项目")
    winning_info = models.JSONField(default=dict, blank=True, verbose_name="中标信息")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='winning_result_announcements', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_winning_result_announcement'
        verbose_name = '中标结果公示'
        verbose_name_plural = '中标结果公示'
        unique_together = ('announcement_date', 'project')
        indexes = [
            models.Index(fields=['announcement_date']),
            models.Index(fields=['original_url']),
            models.Index(fields=['winning_amount']),
        ]

    def __str__(self):
        try:
            names = [c.company_name for c in self.winning_companies.all()]
        except Exception:
            names = []
        if names:
            return f"中标结果公示 - {'、'.join(names)}"
        return f"中标结果公示 - {self.winning_company.company_name}"


class TransactionResult(models.Model):
    """合同签约模型"""
    sign_date = models.DateField(verbose_name="签约日期")
    contract_code = models.CharField(max_length=100, unique=True, verbose_name="合同编号")
    contract_amount = models.DecimalField(max_digits=15, decimal_places=2, verbose_name="合同金额")
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='transaction_results', verbose_name="签约公司")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='transaction_results', verbose_name="关联项目")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='transaction_results', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_transaction_result'
        verbose_name = '合同签约'
        verbose_name_plural = '合同签约'
        indexes = [
            models.Index(fields=['sign_date']),
            models.Index(fields=['contract_code']),
            models.Index(fields=['contract_amount']),
        ]

    def __str__(self):
        return f"合同签约 - {self.contract_code}"


class TenderClarification(models.Model):
    """澄清文件模型"""
    clarification_date = models.DateTimeField(verbose_name="澄清日期")
    clarification_type = models.CharField(max_length=50, verbose_name="澄清类型")
    content = models.TextField(verbose_name="澄清内容")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tender_clarifications', verbose_name="关联项目")
    crawl_task = models.ForeignKey(CrawlTask, on_delete=models.CASCADE, related_name='tender_clarifications', verbose_name="爬虫任务", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'deal_tender_clarification'
        verbose_name = '澄清文件'
        verbose_name_plural = '澄清文件'
        indexes = [
            models.Index(fields=['clarification_date']),
            models.Index(fields=['clarification_type']),
        ]

    def __str__(self):
        return f"澄清文件 - {self.clarification_type}"


class ProjectVersion(models.Model):
    """项目版本主表"""
    project_code = models.CharField(max_length=100, verbose_name="项目编号")
    version_number = models.CharField(max_length=50, verbose_name="版本号")
    html_timestamp = models.DateTimeField(verbose_name="HTML时间戳")
    project_data = models.JSONField(default=dict, verbose_name="项目数据")
    tender_announcements = models.JSONField(default=list, verbose_name="招标公告")
    bid_opening_records = models.JSONField(default=list, verbose_name="开标记录")
    bid_opening_details = models.JSONField(default=list, verbose_name="开标详情")
    bid_evaluation_results = models.JSONField(default=list, verbose_name="评标结果")
    bid_candidates = models.JSONField(default=list, verbose_name="中标候选人")
    winning_result_announcements = models.JSONField(default=list, verbose_name="中标结果公示")
    contract_results = models.JSONField(default=list, verbose_name="合同结果")
    tender_clarifications = models.JSONField(default=list, verbose_name="澄清文件")
    companies = models.JSONField(default=list, verbose_name="企业信息")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'deal_project_version'
        verbose_name = '项目版本'
        verbose_name_plural = '项目版本'
        unique_together = ('project_code', 'html_timestamp')
        indexes = [
            models.Index(fields=['project_code']),
            models.Index(fields=['html_timestamp']),
            models.Index(fields=['version_number']),
        ]

    def __str__(self):
        return f"项目版本 - {self.project_code} v{self.version_number}"


class SubEntityVersion(models.Model):
    """子实体版本表"""
    ENTITY_TYPES = [
        ('project', '项目'),
        ('tender_announcement', '招标公告'),
        ('bid_opening_record', '开标记录'),
        ('bid_opening_detail', '开标详情'),
        ('bid_evaluation_result', '评标结果'),
        ('bid_candidate', '中标候选人'),
        ('winning_result_announcement', '中标结果公示'),
        ('transaction_result', '合同签约'),
        ('tender_clarification', '澄清文件'),
        ('company', '企业'),
    ]

    entity_type = models.CharField(max_length=30, choices=ENTITY_TYPES, verbose_name="实体类型")
    entity_key = models.CharField(max_length=200, verbose_name="实体键")
    hierarchy_path = models.CharField(max_length=500, verbose_name="层级路径")
    version_data = models.JSONField(default=dict, verbose_name="版本数据")
    html_timestamp = models.DateTimeField(verbose_name="HTML时间戳")
    is_active = models.BooleanField(default=True, verbose_name="是否激活")
    change_type = models.CharField(max_length=20, verbose_name="变更类型")  # created, updated, deleted
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'deal_sub_entity_version'
        verbose_name = '子实体版本'
        verbose_name_plural = '子实体版本'
        indexes = [
            models.Index(fields=['entity_type']),
            models.Index(fields=['entity_key']),
            models.Index(fields=['html_timestamp']),
            models.Index(fields=['is_active']),
        ]

    def __str__(self):
        return f"实体版本 - {self.entity_type}:{self.entity_key}"


class VersionRelationship(models.Model):
    """版本关系表"""
    RELATIONSHIP_TYPES = [
        ('project_tender', '项目-招标公告'),
        ('project_opening', '项目-开标记录'),
        ('project_evaluation', '项目-评标结果'),
        ('project_winning', '项目-中标结果'),
        ('project_contract', '项目-合同'),
        ('project_clarification', '项目-澄清文件'),
        ('opening_detail', '开标记录-开标详情'),
        ('evaluation_candidate', '评标结果-中标候选人'),
        ('company_opening', '企业-开标详情'),
        ('company_candidate', '企业-中标候选人'),
        ('company_winning', '企业-中标结果'),
        ('company_contract', '企业-合同'),
    ]

    relationship_type = models.CharField(max_length=30, choices=RELATIONSHIP_TYPES, verbose_name="关系类型")
    source_entity_type = models.CharField(max_length=30, verbose_name="源实体类型")
    source_entity_key = models.CharField(max_length=200, verbose_name="源实体键")
    target_entity_type = models.CharField(max_length=30, verbose_name="目标实体类型")
    target_entity_key = models.CharField(max_length=200, verbose_name="目标实体键")
    relationship_data = models.JSONField(default=dict, verbose_name="关系数据")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'deal_version_relationship'
        verbose_name = '版本关系'
        verbose_name_plural = '版本关系'
        indexes = [
            models.Index(fields=['relationship_type']),
            models.Index(fields=['source_entity_type', 'source_entity_key']),
            models.Index(fields=['target_entity_type', 'target_entity_key']),
        ]

    def __str__(self):
        return f"版本关系 - {self.source_entity_type}:{self.source_entity_key} -> {self.target_entity_type}:{self.target_entity_key}"
